package com.zlc.common.core.sys.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zlc.common.common.exception.BusinessException;
import com.zlc.common.common.service.BaseServiceImpl;
import com.zlc.common.core.sys.model.entity.MayanSysHolidayConfig;
import com.zlc.common.core.sys.mapper.MayanSysHolidayConfigMapper;
import com.zlc.common.core.sys.model.vo.MayanSysHolidayConfigVo;
import com.zlc.common.core.sys.service.MayanSysHolidayConfigService;
import com.zlc.common.util.AssertUtils;
import com.zlc.common.util.DateUtils;
import com.zlc.common.util.LocalDateUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author  zl
 * @date 2025-08-29 
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class MayanSysHolidayConfigServiceImpl extends BaseServiceImpl<MayanSysHolidayConfigMapper, MayanSysHolidayConfig, MayanSysHolidayConfigVo> implements MayanSysHolidayConfigService{

    @Override
    public void setConfig(MayanSysHolidayConfigVo config) {
        AssertUtils.isTrue(!ObjectUtil.isEmpty(config.getYear()),"年份不可为空");
        AssertUtils.isTrue(!ObjectUtil.isEmpty(config.getHolidayFlag()),"设置类型不可为空");
        AssertUtils.isTrue(!ObjectUtil.isEmpty(config.getDate()),"设置日期不可为空");
        if(config.getYear() > 2099 || config.getYear() < 1970){
            throw new BusinessException("年份范围1970-2099");
        }
        if(config.getYear() != LocalDateUtils.dateToLocalDateTime(config.getDate()).getYear()){
            throw new BusinessException("日期和年份不符");
        }
        //查询是否存在
        LambdaQueryWrapper<MayanSysHolidayConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MayanSysHolidayConfig::getYear,config.getYear());
        wrapper.eq(MayanSysHolidayConfig::getDate,config.getDate());
        List<MayanSysHolidayConfigVo> mayanSysHolidayConfigVos = queryVoList(wrapper);
        if(!ObjectUtil.isEmpty(mayanSysHolidayConfigVos)){
            MayanSysHolidayConfigVo mayanSysHolidayConfigVo = mayanSysHolidayConfigVos.get(0);
            mayanSysHolidayConfigVo.setHolidayFlag(config.getHolidayFlag());
            saveVo(mayanSysHolidayConfigVo);
            return;
        }
        saveVo(config);
    }

    @Override
    public Map<String, Boolean> findAllHolidayConfig(Integer year) {
        LambdaQueryWrapper<MayanSysHolidayConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MayanSysHolidayConfig::getYear,year);
        List<MayanSysHolidayConfigVo> mayanSysHolidayConfigVos = queryVoList(wrapper);
        if(ObjectUtil.isEmpty(mayanSysHolidayConfigVos)){
            return new HashMap<>();
        }
        return mayanSysHolidayConfigVos.stream().collect(Collectors.toMap(MayanSysHolidayConfigVo::getDateStr, MayanSysHolidayConfigVo::getHolidayFlag));
    }
}
